#!/usr/bin/env python
# coding=utf-8

import random
import hashlib
import json
from datetime import date, datetime

class utils(object):
    #返回随机数
    @staticmethod
    def GetRandom():
        return random.random()

    @classmethod
    def escape_string(value):
        value = value.replace("'", "\\'")
        value = value.replace('"', '\\"')
        return value

    @classmethod
    def Md5(self,key):
        return hashlib.md5(key.encode(encoding="UTF-8")).hexdigest()

    @classmethod
    def ListToJsonify(cls,list):
        result = []
        for info in list:
            result.append(info.to_json())
        from flask import jsonify
        return jsonify(result)

    #翻页
    @classmethod
    def Pagesize(self,indexIndex=1, totalcount=0, pagecount=0, url=''):
        _len_ = 5
        indexIndex = int(indexIndex)
        li_Front = li_after = ''
        after = front = 0
        for i in range(1, _len_):
            after = indexIndex + i
            front = indexIndex - i
            if after <= pagecount:
                li_after = '%s<li><a class="page-link" href="%s/%s">%s</a></li>' % (li_after, url, after, after)
            if front >= 1:
                li_Front = '<li><a class="page-link" href="%s/%s">%s</a></li>%s' % (url, front, front, li_Front)

        if indexIndex - 1 < 1:
            li = '<li class="paginate_button page-item previous disabled"><a class="page-link" href="%s/1">第一页</a></li>' % url
            li = '%s<li class="paginate_button page-item previous disabled"><a class="page-link">上一页</a></li>' % (li)
        else:
            li = '<li><a href="%s/1" class="page-link">第一页</a></li>' % url
            li = '%s<li><a href="%s/%s" class="page-link">上一页</a></li>' % (li, url, (indexIndex - 1))

        li = '%s%s<li class="paginate_button page-item active""><a class="page-link">%s</a></li>%s' % (
        li, li_Front, indexIndex, li_after)

        if indexIndex + 1 > pagecount:
            li = '%s<li class="disabled"><a class="page-link">下一页</a></li>' % (li)
            li = '%s<li class="disabled"><a class="page-link">最后一页</a></li>' % (li)
        else:
            li = '%s<li><a href="%s/%s" class="page-link">下一页</a></li>' % (li, url, (indexIndex + 1))
            li = '%s<li><a href="%s/%s" class="page-link">最后一页</a></li>' % (li, url, pagecount)

        li = '%s<li class="paginate_button page-item previous disabled"><span class="page-link">共%s页/%s条</span></li>' % (
        li, pagecount, totalcount)
        ul = '<ul class="pagination float-right" style="margin-bottom:0">%s</ul>' % li

        return ul


class AlchemyEncoder(json.JSONEncoder):
    def default(self, obj):
        from sqlalchemy.ext.declarative import DeclarativeMeta
        if isinstance(obj.__class__, DeclarativeMeta):
            # an SQLAlchemy class
            fields = {}
            for field in [x for x in dir(obj) if not x.startswith('_') and hasattr(obj.__getattribute__(x), '__call__') == False and x != 'metadata']:
            #for field in [x for x in dir(obj) if "_sa_instance_state" in x.__dict__]:
                data = obj.__getattribute__(field)
                try:
                    json.dumps(data) # this will fail on non-encodable values, like other classes
                    fields[field] = data
                except TypeError:
                    fields[field] = None
            # a json-encodable dict
            return fields

        return json.JSONEncoder.default(self, obj)


class chemyEncoder(json.JSONEncoder):
    def default(self, obj):
        dict = obj.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict




class JsonEncoder(json.JSONEncoder):
    def default(self, obj):
        # if isinstance(obj, datetime.datetime):
        #     return int(mktime(obj.timetuple()))
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        #if isinstance(obj, numpy.ndarray):
        #    return obj.tolist()
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


#reluesInfo
class reluesInfo(object):
    def __init__(self,status=0,msg="None",relues="None"):
        self.status=status
        self.msg=msg
        self.relues=relues


    def dumps(self):
        #print(isinstance(self.relues,object))
        #return self.__dict__
        jsonstr = json.dumps(self.__dict__,cls=JsonEncoder, indent=4)
        return jsonstr

class formerrors(object):
    def __init__(self,forms):
        self.forms = forms

    def todict(self):
        _err_dict = {}
        for filed in self.forms:
            if len(filed.errors)>0:
                for err in filed.errors:
                    _err_dict[filed.id] = err
        return _err_dict



